<?php
namespace Admin\Model;
use Think\Model;
class GoodsModel extends Model {

		protected $_validate = array(
				array('goods_name','require','商品名不得为空！',1), //默认情况下用正则进行验证
				array('market_price','require','市场价格不得为空！',1), //默认情况下用正则进行验证
				array('shop_price','require','本店价格不得为空！',1), //默认情况下用正则进行验证
				array('goods_name','','帐号名称已经存在！',0,'unique',1), // 在新增的时候验证name字段是否唯一
		);
		
		
		public function _before_update($data,$option){
			//处理从商品修改界面传递过来的（是否上架）的数据
			if($_POST['onsale']){
					 $_POST['onsale']=1;
				 }else{
					 $_POST['onsale']=0;
				 }
			//处理从商品修改界面传递过来的修改主图，删除原来的四张图片
			if($_FILES['original'][tmp_name]){
				$pics=D('goods')->field('original,max_thumb,mid_thumb,sm_thumb')->find($option['where']['id']);
				$original='./'.$pics['original'];
				$max_thumb='./'.$pics['max_thumb'];
				$mid_thumb='./'.$pics['mid_thumb'];
				$sm_thumb='./'.$pics['sm_thumb'];
				if(file_exists($original)){
					unlink($original);
				}
				if(file_exists($max_thumb)){
					unlink($max_thumb);
				}
				if(file_exists($mid_thumb)){
					unlink($mid_thumb);
				}
				if(file_exists($sm_thumb)){
					unlink($sm_thumb);
				}
			}
			
			//处理从商品修改表单传递过来的会员价格信息，如果有数据先删除原来的数据，再添加一个新的数据
			$mpres=I('mp');
			$mp=D('memberPrice');
			if($mpres){
			$mp->where(array('goods_id'=>$option['where']['id']))->delete();
				//遍历从会员价格栏传递过来的会员价格，并存放到会员价格表中
					foreach($mpres as $k=>$v){
							if(trim($v)!=''){
								$mp->add(array(
										'price'=>$v,
										'lever_id'=>$k,
										'goods_id'=>$option['where']['id']
										));
								}
						}
				}
				
				//<11111111111111111111111111111111111>
				
				if($this->hasImg($_FILES['goods_pics']['tmp_name'])){
					 $upload = new \Think\Upload();// 实例化上传类
					 $upload->maxSize   =     3145728 ;// 设置附件上传大小 
					 $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 
					 $upload->savePath  =      './Public/Uploads/Goods/'; // 设置附件上传目录
					 $upload->rootPath  =      './'; // 设置附件上传目录
					// $upload->autoSub   =     false;// 设置图片上传不生成子目录
					 $info   =   $upload->upload(array('goods_pics'=>$_FILES['goods_pics'])); 
					
					 $image = new \Think\Image();
					 $goodspic=M('goods_pic');
					 foreach($info as $k=>$v){
						 $original=$v['rootPath'] . $v['savepath'] . $v['savename']; 
						 $image->open($original);
						 $max_thumb=$v['rootPath'] . $v['savepath'] . 'max'.$v['savename']; 
						 $sm_thumb=$v['rootPath'].$v['savepath'].'sm_'.$v['savename'];
						 $image->thumb(362, 362)->save($max_thumb);
						 $image->thumb(67, 67)->save($sm_thumb);
						 $goodspic->add(array(
									'goods_id'=>$option['where']['id'],
									'original'=>$original,
									'max_thumb'=>$max_thumb,
									'sm_thumb'=>$sm_thumb
						 ));
					 }
							
				}
				//处理商品属性  修改商品属性
				$goods_attr=I('old_goods_attr');
				$goods_price=I('old_goods_price');
				if($goods_attr){
					$ids=array_keys($goods_price);
					$prices=array_values($goods_price);
				//	dump($ids);dump($prices);die;
					$goodsattr=D('GoodsAttr');
					$i=0;
					foreach($goods_attr as $k=>$v){
						if(is_array($v)){
							foreach($v as $k1=>$v1){
								$goodsattr->where(array('id'=>$ids[$i]))->save(array(
									'attr_value'=>$v1,
									'attr_pric'=>$prices[$i],
								));
								$i++;
							}
						}else{
									$goodsattr->where(array('id'=>$ids[$i]))->save(array(
									'attr_value'=>$v,
									'attr_pric'=>$prices[$i],
								));
							$i++;
						}
					}
				}
				
				//<11111111111111111111111111111111111>
		}

		//用查询到的所有数据，调用递归函数，得到排好序后栏目结果的数组；
		public function catetree(){
			$data = $this->order("id desc")->select();
			return $this->tree($data);
		}
		
		
		//使用递归方式对商品栏目列表进行排序，返回排序好后的一个数组
		public function tree($data,$pid=0,$level=0){
			static $arr=array();
			foreach($data as $K=>$v){
				if($v['pid']==$pid){
					$v['level']=$level;
					$arr[]=$v;
					$this->tree($data,$v['id'],$level+1);
				}
			}
			return $arr;
		}
		
		
		public function catedel($id){
			$datas = $this->select();
			$res =$this->tigei($datas,$id);
			$res['aaa']=$id;
			return $res;
		}
		
		public function tigei($datas,$id){
		static $arr=array();

			foreach($datas as $k=>$vo){
				if($vo['pid']==$id){
					$arr[]=$vo['id'];
					$this->tigei($datas,$vo['id']);
				}
			}
			return $arr;
		}
		
		
		public function _after_insert($data,$option){
			
			//取得会员价格栏中传递过来的值
			$mpres=I('mp');
			if($mpres){
					$mp=D('memberPrice');
				//遍历从会员价格栏传递过来的会员价格，并存放到会员价格表中
					foreach($mpres as $k=>$v){
							if(trim($v)!=' '){
								$mp->add(array(
										'price'=>$v,
										'lever_id'=>$k,
										'goods_id'=>$data['id']
										));
								}
						}
				}
				//上传图片到商品图片表中
				if($this->hasImg($_FILES['goods_pics']['tmp_name'])){
					 $upload = new \Think\Upload();// 实例化上传类
					 $upload->maxSize   =     3145728 ;// 设置附件上传大小 
					 $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 
					 $upload->savePath  =      './Public/Uploads/Goods/'; // 设置附件上传目录
					 $upload->rootPath  =      './'; // 设置附件上传目录
					// $upload->autoSub   =     false;// 设置图片上传不生成子目录
					 $info   =   $upload->upload(array('goods_pics'=>$_FILES['goods_pics'])); 
					
					 $image = new \Think\Image();
					 $goodspic=M('goods_pic');
					 foreach($info as $k=>$v){
						 $original=$v['rootPath'] . $v['savepath'] . $v['savename']; 
						 $image->open($original);
						 $max_thumb=$v['rootPath'] . $v['savepath'] . 'max'.$v['savename']; 
						 $sm_thumb=$v['rootPath'].$v['savepath'].'sm_'.$v['savename'];
						 $image->thumb(362, 362)->save($max_thumb);
						 $image->thumb(67, 67)->save($sm_thumb);
						 $goodspic->add(array(
									'goods_id'=>$data['id'],
									'original'=>$original,
									'max_thumb'=>$max_thumb,
									'sm_thumb'=>$sm_thumb
						 ));
					 }
							
				}
				
				//处理商品属性  新增加商品属性
				$goods_attr=I('goods_attr');
				$goods_price=I('goods_price');
				if($goods_attr){
					$goodsattr=D('GoodsAttr');
					$i=0;
					foreach($goods_attr as $k=>$v){
						if(is_array($v)){
							foreach($v as $k1=>$v1){
								$goodsattr->add(array(
									'goods_id'=>$data['id'],
									'attr_id'=>$k,
									'attr_value'=>$v1,
									'attr_pric'=>$goods_price[$i],
								));
								$i++;
							}
						}else{
							$goodsattr->add(array(
							'goods_id'=>$data['id'],
							'attr_id'=>$k,
							'attr_value'=>$v,
							'attr_pric'=>$goods_price[$i],
							));
							$i++;
						}
					}
				}
				//处理商品的推荐位
				$recid=I('recid');
				if($recid){
					foreach($recid as $k=>$v){
					D('recvalue')->add(array(
										'valueid'=>$data['id'],
										'recid'=>$v,
										'rectype'=>1
									));
					}
				}

		}
		
		
		public function _after_update($data,$option){
			
			D('recvalue')->where(array('valueid'=>$option['where']['id'],'rectype'=>1))->delete();
					//处理商品的修改推荐位
				$recid=I('recid');
				if($recid){
					foreach($recid as $k=>$v){
					D('recvalue')->add(array(
										'valueid'=>$data['id'],
										'recid'=>$v,
										'rectype'=>1
									));
					}
				}
		}

		public function hasImg($files){
			foreach($files as $k=>$v){
				if($v){
					return true;
				}
			}
			return false;
		}
		
		
		public function _before_delete($option){
			$id=$option['where']['id'];
		/*	$this->field('original,max_thumb,mid_thumb,sm_thumb')->find($id);
			//处理主图缩略图
			@unlink($this->original);
			@unlink($this->max_thumb);
			@unlink($this->mid_thumb);
			@unlink($this->sm_thumb);
			//删除商品的会员价格
			D('memberPrice')->where(array('goods_id'=>$id))->delete();
			//删除商品的属性；
			D('goodsAttr')->where(array('goods_id'=>$id))->delete();
			$goodspicres=D('goodsPic')->where(array('goods_id'=>$id))->selece();
			foreach($goodspicres as $k=>$v){
				@unlink($v['original']);
				@unlink($v['max_thumb']);
				@unlink($v['sm_thumb']);
			}
			D('GoodsPic')->where(array('goods_id'=>$id))->delete();
			*/
			D('recvalue')->where(array('rectype'=>1,'valueid'=>$id))->delete();
			
		}
		
		
		//取得当前商品的单选属性
		public function getRadioAttr($goodsid){
			$sql="SELECT a.id,a.attr_id,a.attr_value,b.attr_name 
							FROM sp_goods_attr a LEFT JOIN sp_attr b ON a.attr_id=b.id
							WHERE a.goods_id=$goodsid AND b.attr_type='1'";
							return $this->query($sql);
		}
}